import wx

class MyFrame(wx.Frame):
    btn_pos_x, btn_pos_y = 20, 70
    btn_size_w, btn_size_y = 50, 50
    def __init__(self):
        # 创建窗口
        super().__init__(None, title='简单计算器', size=(400, 600), pos=(100, 100))
        # 创建面板
        self.pl = wx.Panel(self, pos=(0, 0), size=(350, 400))

        # 创建文本框
        self.displayBox = wx.TextCtrl(self.pl, pos=(20, 10), size=(350, 50), style=wx.TE_RIGHT)

        # 创建按钮
        self.btn_1 = wx.Button(self.pl, label='1', size=(MyFrame.btn_size_w, MyFrame.btn_size_y), pos=(MyFrame.btn_pos_x, MyFrame.btn_pos_y))
        self.btn_2 = wx.Button(self.pl, label='2', size=(MyFrame.btn_size_w, MyFrame.btn_size_y), pos=(MyFrame.btn_pos_x + 60, MyFrame.btn_pos_y))
        self.btn_3 = wx.Button(self.pl, label='3', size=(MyFrame.btn_size_w, MyFrame.btn_size_y), pos=(MyFrame.btn_pos_x + 120, MyFrame.btn_pos_y))
        self.btn_4 = wx.Button(self.pl, label='4', size=(MyFrame.btn_size_w, MyFrame.btn_size_y), pos=(MyFrame.btn_pos_x + 180, MyFrame.btn_pos_y))
        self.btn_add = wx.Button(self.pl, label='+', size=(MyFrame.btn_size_w, MyFrame.btn_size_y), pos=(MyFrame.btn_pos_x, MyFrame.btn_pos_y + 60))
        self.btn_equal = wx.Button(self.pl, label='=', size=(MyFrame.btn_size_w, MyFrame.btn_size_y), pos=(MyFrame.btn_pos_x + 60, MyFrame.btn_pos_y + 60))
        # 按钮事件
        self.Bind(wx.EVT_BUTTON, self.on_btn_1, self.btn_1)
        self.Bind(wx.EVT_BUTTON, self.on_btn_2, self.btn_2)
        self.Bind(wx.EVT_BUTTON, self.on_btn_3, self.btn_3)
        self.Bind(wx.EVT_BUTTON, self.on_btn_4, self.btn_4)
        self.Bind(wx.EVT_BUTTON, self.on_btn_add, self.btn_add)
        self.Bind(wx.EVT_BUTTON, self.on_btn_equal, self.btn_equal)


    def on_btn_1(self, event):
        self.displayBox.AppendText('1')


    def on_btn_2(self, event):
        self.displayBox.AppendText('2')


    def on_btn_3(self, event):
        self.displayBox.AppendText('3')


    def on_btn_4(self, event):
        self.displayBox.AppendText('4')


    def on_btn_add(self, event):
        self.displayBox.AppendText('+')


    def on_btn_equal(self, event):
        text = self.displayBox.GetValue()
        # 移除等号
        expression = text.replace('=', '')
        try:
            result = str(eval(expression))
            self.displayBox.SetValue(result)
        except Exception as e:
            self.displayBox.SetValue("Error")




if __name__ == '__main__':
    # 创建应用程序对象
    app = wx.App()
    # 创建窗口类
    frm = MyFrame()
    frm.Show()
    # 让窗口一直显示
    app.MainLoop()